#include <REGX52.H>
#include <stdlib.H>
#include "AT24C02.h"
#include "Buzzer.h"
#include "Delay.h"
#include "MatrixLED.h"
#include "Timer0.h"
#include "Key.h"

unsigned char Dire,KeyNum,length,foodx,foody,Speed=1000;
char Snakex[64]={0};
char Snakey[64]={0};
unsigned char code Coory[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};

void SnakeMove()//蛇身移动
{	unsigned char i;
    for (i=length+11;i>0;i--)
    {
        Snakex[i]=Snakex[i-1];
        Snakey[i]=Snakey[i-1];
    }	
	switch(Dire)	//Dire：方向（1：上 2：下 3：左 4：右）
	{
		case 1:(Snakex[0])--;if((Snakex[0])<0){(Snakex[0])=7;}break;
		case 2:(Snakex[0])++;(Snakex[0])%=8;break;
		case 3:(Snakey[0])++;(Snakey[0])%=8;break;
		case 4:(Snakey[0])--;if((Snakey[0])<0){(Snakey[0])=7;}break;
	}
}
void Scan_Key()	//检测按键改变方向
{
	if(KeyNum)
	{
		switch(KeyNum)
		{
			case 1:if(Dire!=3)Dire=4;break;
			case 2:if(Dire!=4)Dire=3;break;
			case 3:if(Dire!=2)Dire=1;break;
			case 4:if(Dire!=1)Dire=2;break;
		}
	}
}
void food()//食物坐标
{	
	foodx=(rand()+Snakex[length-1])%8;
	foody=(rand()+Snakex[length-1])%8;
}
void PlaySnakeAC()//刷新蛇、食物动画
{
	unsigned char i;
	for(i=0;i<length+1;i++)
	{
        MatrixLED_ShowColumn(Snakex[i],Coory[Snakey[i]]);
        MatrixLED_ShowColumn(foodx,Coory[foody]);
	}
}
void Snakedead()//判断死亡，游戏结束
{	unsigned char i,m,n;
	for(i=4;i<=length;i++)
	{
		if(Snakex[0]==Snakex[i] && Snakey[0]==Snakey[i])//蛇头撞到自己，游戏结束
		{
			P0=0xFF;
            AT24C02_WriteByte(14,length);
            Delay(5);
            if(length>AT24C02_ReadByte(15))
            {
                AT24C02_WriteByte(15,length);
                Delay(5);
            }
            if(length>AT24C02_ReadByte(16)&&length<AT24C02_ReadByte(15))
            {
                AT24C02_WriteByte(16,length);
                Delay(5);
            }
            if(length>AT24C02_ReadByte(17)&&length<AT24C02_ReadByte(16))
            {
                AT24C02_WriteByte(17,length);
                Delay(5);
            }
			while(1);		
		}
	}
}
void Play_Game()
{	unsigned char i;
	Scan_Key();
	PlaySnakeAC();
	Snakedead();
	for(i=0;i<length;i++)//扫描是否吃到食物
	{	
		if(foodx==Snakex[i] && foody==Snakey[i])
		{
			length++;
			food();
		}
	}
}


void main()
{
    Timer0_Init();
    MatrixLED_Init();
    food();
    length=1;		//初始化长度
	Dire=3;			//初始化方向：下
	while(1)
	{
		rand();
		KeyNum=Key();
		Play_Game();
	}
}

void Timer0_Routine() interrupt 1
{
    static unsigned int T0Count1,T0Count2;
    TL0 = 0x18; //设置定时初值
    TH0 = 0xFC; //设置定时初值
    T0Count1++;
    if(T0Count1>=15)
    {
		T0Count1=0;
		Key_Loop();
    }
    T0Count2++;
	if(T0Count2>Speed)
	{	
		T0Count2=0;
		SnakeMove();
	}

}